<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\tool\Result;
use think\Response;
use app\common\model\Exchange as ExchangeModel;
use think\exception\ValidateException;

class Exchange extends Base
{
    public function index(): Response
    {
        $result['account'] = [
            [
                'title' => get_pay_way('currency'),
                'type' => 'currency',
                'balance' => $this->user->assets->currency,
                'take' => [
                    [
                        'title' => get_pay_way('green'),
                        'type' => 'green',
                        'balance' => $this->user->assets->green
                    ]
                ]
            ],
            [
                'title' => get_pay_way('green'),
                'type' => 'green',
                'balance' => $this->user->assets->green,
                'take' => [
                    [
                        'title' => get_pay_way('currency'),
                        'type' => 'currency',
                        'balance' => $this->user->assets->currency
                    ]
                ]
            ]
        ];
        $result['factor'] = [
            'exchange_open' => $this->system['exchange_open'],
            'exchange_min' => $this->system['exchange_min'],
            'exchange_bs' => $this->system['exchange_bs'],
            'exchange_cost' => $this->system['exchange_cost'],
            'exchange_msg' => handleRichText($this->system['exchange_msg'])
        ];

        return Result::success('success', $result);
    }

    public function save(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'Exchange');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(ExchangeModel::add($param, $this->user, $this->system));
    }

    public function record(): Response
    {
        return Result::fastReturn(ExchangeModel::getPageList(['uid' => $this->user->id],
            'id,account,take_account,amount,cost,real_amount,create_time',
            $this->getPage(), $this->getLimit(), false));
    }
}